﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.SqlClient;

namespace WSweb
{
    public partial class Login : System.Web.UI.Page
    {
        private string user;
        private string passw;

        private SqlConnection c = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DBwswebCS"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Header.Title = "WSweb - Login";
            user = Request.Form["username"].ToString();
            passw = Request.Form["password"].ToString();
            c.Open();
            SqlCommand comm1 = new SqlCommand("select salt from Korisnik where username = @username", c);
            comm1.Parameters.AddWithValue("@username", user);
            SqlDataReader sdr1 = comm1.ExecuteReader();
            if (sdr1.Read())
            {
                string salt = sdr1["salt"].ToString();
                sdr1.Close();
                string HashedPassword = CreatePasswordHash(passw, salt);
                SqlCommand comm2 = new SqlCommand("select * from Korisnik where username = @username and password = @password", c);
                comm2.Parameters.AddWithValue("@username", user);
                comm2.Parameters.AddWithValue("@password", HashedPassword);
                SqlDataReader sdr2 = comm2.ExecuteReader();
                if (sdr2.Read())
                {
                    Session["korisnik"] = user;
                    Session["ovlasti"] = sdr2["id_auth"].ToString();
                    Session.Timeout = 15;
                    Response.Redirect("Admin.aspx");
                }
                else
                {
                    Label1.Text = "Neispravan login!";
                }
                sdr2.Close();
                c.Close();
            }
            else
            {
                c.Close();
                Response.Redirect("Default.aspx");
            }
            
        }


        private static string CreatePasswordHash(string pwd, string salt)
        {
            string saltedHash = String.Concat(String.Concat(salt, pwd), salt);
            saltedHash = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedHash, "sha1");
            return saltedHash;
        }
    }
}